<template>
  <!-- 随访详情 -->
  <section>
    <div style="border-bottom:1px solid #eee;padding-bottom:10px;">
      <el-page-header @back="goBack" :content="form.status==3?'随访记录':'开始随访'">
      </el-page-header>
    </div>
    <br>
    <div style="display: flex;">
      <div style="flex-shrink: 0;margin-right:15px;">
        <patientBasicInfo v-if="visitDetail.patientId" :patientId="visitDetail.patientId"></patientBasicInfo>
      </div>
      <div style=" flex-grow: 1;">
        <h3 style="margin:0;">随访内容</h3>
        <hr>
        <table style="border:none;width:100%;">
          <tr style="height:35px;">
            <td>计划创建日期：{{visitDetail.createTime}}</td>
            <td>计划创建人：{{visitDetail.createUserName}}</td>
            <td>计划随访日期：{{visitDetail.scheduleVisitTime}}</td>
            <td>计划执行人：{{visitDetail.scheduleVisitUserName}}</td>
          </tr>
          <tr style="height:35px;">
            <td>主管医生：{{visitDetail.managerDoctorName}}</td>
            <td>随访类型：{{visitDetail.visitTypeName}}</td>
          </tr>
          <tr style="height:35px;">
            <td colspan="4">随访内容：{{visitDetail.visitContent}}</td>
          </tr>
        </table>
        <hr>
        <div class="form-tool" style=" align-items: center;">
          <div>
            <table style="width:100%;border:0;">
              <tr>
                <td width="120px;">
                  <h3 style="margin:0;">随访结果</h3>
                </td>
                <td>
                  <el-select v-if="form.status==3" v-model="visitResultMB.visitIndexObj" value-key="visitTime" placeholder="随访次数" @change="getHistoryRecord">
                    <el-option v-for="(item,index) in resultList" :key="index" :value="item" :label="index+1"></el-option>
                  </el-select>
                </td>
              </tr>
            </table>
          </div>
          <div v-if="form.status!=3">
            <el-select v-model="visitResultMB.id" placeholder="选择结论模板" filterable remote clearable :remote-method="getResetPage" @clear="getResetPage" @change="onChangeReset">
              <el-option v-for="(item,index) in visitResultMB.list" :key="index" :value="item.id" :label="item.templateName"></el-option>
              <br>
              <pager v-model="visitResultMB.pager" small @change-pagenum="getVisitResult"></pager>
            </el-select>
          </div>
        </div>
        <br>
        <el-form label-position="top">
          <el-row :gutter="20">
            <el-col :span="6">
              <el-form-item label="随访时间：" prop="visitTime">
                <el-date-picker :disabled="form.status==3" v-model="form.visitTime" value-format="yyyy-MM-dd HH:mm:ss" type="datetime" placeholder="请选择">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="随访人员：" prop="visitUserId">
                <userSearch :disabled="form.status==3" v-if="visitResultMB.showVisitUser" v-model="form.visitUserId" :keyword="initSearch.visitUserName" placeholder="请选择"></userSearch>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="随访方式：" prop="visitWay">
                <el-select :disabled="form.status==3" v-model="form.visitWay" placeholder="请选择">
                  <el-option v-for="(item,index) in visitWayEnum" :key="index" :value="item.id" :label="item.desc"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <br>
        <el-form :disabled="form.status==3" label-width="120px" @submit.native.prevent="onSubmit(0)">
          <div v-for="(item,index) in visitTypeItem" :key="item.id">
            <h3 style="margin:0 0 30px 0;">{{item.name}}</h3>
            <!-- <el-row>
              <el-col :span="6"></el-col>
            </el-row> -->
            <div v-for="(item2,index2) in item.list" :key="item2.type+''+index2">
              <div v-if="item2.type!=0" style="padding:0 0 10px 20px;color:#999;">{{item2.type|changeAssist(visitItemEnum)}}</div>
              <el-row>
                <template v-for="(item3,index3) in item2.list">
                  <el-col v-if="item3.unit" :span="8" :key="item3.id+''+index3">
                    <el-form-item :label="item3.name+'：'">
                      <el-input v-model="item3.answer" :placeholder="item3.placeholder">
                        <template slot="append">{{item3.unit}}</template>
                      </el-input>
                    </el-form-item>
                  </el-col>
                  <el-col v-else :span="24" :key="item3.id+''+index3">
                    <el-form-item :label="item3.name+'：'">
                      <el-input v-if="item3.displayControl==1" v-model="item3.answer" :placeholder="item3.placeholder" type="textarea" :rows="2"></el-input>
                      <el-input v-else-if="item3.displayControl==2" v-model="item3.answer" :placeholder="item3.placeholder"></el-input>
                    </el-form-item>
                  </el-col>
                </template>
              </el-row>
            </div>
          </div>
          <el-form-item label="随访结论：">
            <el-input  v-model="form.visitResult" placeholder="" type="textarea" :rows="3"></el-input>
          </el-form-item>
          <el-form-item label="附件：">
            <div style="color:#ccc;">
              支持：doc,docx,xls,xlsx,pdf,png,jpg,
            </div>
            <largeUpFile v-if="form.status!=3" v-model="upFileObj.vModel" :limitType="upFileObj.limitType"></largeUpFile>
            <div v-else>
              <div v-for="(item,index) in visitResultMB.fileUrls" :key="index" style="line-height:20px;">
                <el-link type="primary" :href="item|imageUrl" style="margin:0 10px 10px 0;">{{item}}</el-link>
              </div>
            </div>
          </el-form-item>
          <el-button v-show="false" :loading="btnLoading" native-type="submit"></el-button>
        </el-form>
        <div v-if="form.status!=3" style="padding-top:15px;margin-top:15px;border-top:1px solid #ccc;">
          <el-button :loading="btnLoading" type="danger" @click="onSubmit(1)">结案并保存</el-button>
          <el-button :loading="btnLoading" type="primary" @click="onSubmit(0)">保存</el-button>
        </div>
      </div>
    </div>
  </section>
</template>
<script>
export default {
  components: {
    patientBasicInfo: () => import("@/pages/_com/patientBasicInfo.vue"),
    userSearch: () => import("@/pages/_com/userSearch.vue"),
    largeUpFile: () => import("@/components/largeUpFile.vue")
  },
  data() {
    return {
      btnLoading: false,
      initSearch: {
        visitUserName: ""
      },
      //随访结论模板
      visitResultMB: {
        pager: { pageSize: 10, pageNum: 1, total: 0 },
        name: "",
        list: [],
        id: "",
        showVisitUser: false,
        fileUrls: [], //文件地址
        visitIndexObj: null //选择的随访次
      },
      qxBtns: {},
      visitDetail: {}, //随访任务详情
      visitTypeItem: [], //随访类型下的项目
      visitWayEnum: [], //随访方式
      visitItemEnum: [], //随访分类枚举
      resultList: [], //查看随访结果
      form: {
        id: "", //结论id
        followUpVisitId: "", //随访id
        visitTime: "",
        visitUserId: "",
        visitWay: "",
        visitResult: "",
        visitUrls: "",
        answer: "",
        visitUrls: "",
        isClose: 0, //默认不结束
        //==============
        status: ""
      },
      upFileObj: {
        vModel: [],
        limitType: [
          "image/png",
          "image/jpeg",
          "application/msword",
          "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
          "application/pdf",
          "application/vnd.ms-excel",
          "application/x-xls",
          "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
        ]
      }
    };
  },
  created() {
    const th = this;
    th.form.visitUserId = Number.parseInt(th.adminUser.memberId);
    th.initSearch.visitUserName = th.adminUser.memberName;
    th.form.followUpVisitId = th.jieMi(th.$route.query.id);
    th.form.status = th.$route.query.status;
  },
  async mounted() {
    const th = this;
    th.visitItemEnum = await th.getCommonConfigByKey("随访子项分类");
    const fn = function() {
      th.getQX();
      if (th.form.status == 3) {
        th.followUpVisitdetailvisited();
      } else {
        th.getVisitDetail();
        th.visitResultMB.showVisitUser = true;
      }
    };
    th.verifyUrlAttack().then(res => {
      fn();
    });
    th.getCommonConfigByKey("随访方式").then(res => {
      th.visitWayEnum = res;
    });
  },
  methods: {
    onSubmit(type) {
      const th = this;
      let j = {};
      if (!th.form.visitTime) {
        th.$message.warning("请选择随访时间");
        return;
      }
      if (!th.form.visitUserId) {
        th.$message.warning("请选择随访人员");
        return;
      }
      if (!th.form.visitWay) {
        th.$message.warning("请选择随访方式");
        return;
      }
      th.form.isClose = type;
      Object.assign(j, th.form);
      //添加文件地址
      j.visitUrls = th.upFileObj.vModel.join(",");
      //处理填写数据
      let answer = [];
      th.visitTypeItem.forEach(d => {
        let j = {
          id: d.id,
          questionAnswerBeans: []
        };
        d.list.forEach(d2 => {
          d2.list.forEach(d3 => {
            let j2 = {
              id: d3.id,
              answer: d3.answer,
              displayControl: d3.displayControl
            };
            j.questionAnswerBeans.push(j2);
          });
        });
        answer.push(j);
      });
      j.answer = JSON.stringify(answer);
      th.btnLoading = true;
      th.$api
        .followUpVisitaddvisitResult(j)
        .then(res => {
          if (res.executed) {
            th.$message.success("保存成功");
            th.goBack();
          } else {
            th.$message.error(res.message);
          }
          th.btnLoading = false;
        })
        .catch(res => {
          th.btnLoading = false;
        });
    },
    //读取历史记录
    getHistoryRecord() {
      const th = this;
      let resultData = th.visitResultMB.visitIndexObj;
      th.form.visitTime = resultData.visitTime;
      th.form.visitUserId = resultData.visitUserId;
      th.form.visitWay = resultData.visitWay;
      th.form.visitResult = resultData.visitResult;
      //查询随访人员
      th.visitResultMB.visitUserName = resultData.visitUserName;
      if (resultData.visitUrls) {
        th.visitResultMB.fileUrls = resultData.visitUrls.split(",");
      }
      //对模板项进行赋值
      th.analyzeData(resultData.answerInfoBeans, true);
    },
    //已随访详情
    followUpVisitdetailvisited() {
      const th = this;
      let j = {
        id: th.form.followUpVisitId
      };
      th.$api.followUpVisitdetailvisited(j).then(res => {
        if (res.executed) {
          th.visitDetail = res.data.followUpVisitContentVO;
          const result = res.data.followUpVisitResultVOS;
          th.resultList = result;
          if (result && result.length > 0) {
            th.visitResultMB.visitIndexObj = result[0];
            th.getHistoryRecord();
            th.visitResultMB.showVisitUser = true;
          }
        }
      });
    },
    //获取随访详情
    getVisitDetail() {
      const th = this;
      let j = {
        id: th.form.followUpVisitId
      };
      th.$api.followUpVisitcontentid(j).then(res => {
        if (res.executed) {
          th.visitDetail = res.data;
          th.getVisitResult();
          th.followUpVisitTypechoicedetail();
        }
      });
    },
    //查询随访类型下的项目（已勾选）
    followUpVisitTypechoicedetail() {
      const th = this;
      let j = {
        id: th.visitDetail.visitTypeId
      };
      th.$api.followUpVisitTypechoicedetail(j).then(res => {
        if (res.executed) {
          th.analyzeData(res.data.questionClassificationInfoBeans);
        }
      });
    },
    //分析类型下的项目
    analyzeData(arr, type) {
      const th = this;
      let list = [];
      arr.forEach(ele => {
        let j = {
          id: ele.id,
          name: ele.name,
          list: []
        };
        let questionBeans = type
          ? ele.questionAnswerInfoBeans
          : ele.questionBeans;
        questionBeans.forEach(ele2 => {
          ele2.type = ele2.type || 0;
          //判断相同类型
          let data = j.list.find(d => {
            return d.type == ele2.type;
          });
          if (data) {
            data.list.push(ele2);
          } else {
            j.list.push({
              type: ele2.type,
              list: [ele2]
            });
          }
        });
        list.push(j);
      });
      th.visitTypeItem = list;
    },
    //随访结论分页
    getVisitResult() {
      const th = this;
      let j = {
        visitTypeId: th.visitDetail.visitTypeId,
        templateName: th.visitResultMB.name
      };
      Object.assign(j, th.visitResultMB.pager);
      th.$api.followUpVisitResultTemplatepageQuery(j).then(res => {
        if (res.executed) {
          th.visitResultMB.list = res.dataBody.list;
          th.visitResultMB.pager.total = res.dataBody.total;
        }
      });
    },
    //随访结论搜索
    getResetPage(name) {
      const th = this;
      th.visitResultMB.pager.pageNum = 1;
      th.visitResultMB.name = name;
      th.getVisitResult();
    },
    //获取模板结论详情
    onChangeReset() {
      const th = this;
      if (!th.visitResultMB.id) return;
      let j = {
        id: th.visitResultMB.id
      };
      th.$api.followUpVisitResultTemplatedetail(j).then(res => {
        if (res.executed) {
          fn(res.data.answerInfoBeans);
          th.form.visitResult = res.data.result;
        }
      });
      //对模板项进行赋值
      const fn = function(arr) {
        arr.forEach(ele => {
          //查找对应显示数据
          let data = th.visitTypeItem.find(d => {
            return d.id == ele.id;
          });
          if (data) {
            //循环子项赋值
            data.list.forEach(d2 => {
              d2.list.forEach(d3 => {
                let data2 = ele.questionAnswerInfoBeans.find(d4 => {
                  return d4.id == d3.id;
                });
                if (data2) {
                  th.$set(d3, "answer", data2.answer);
                }
              });
            });
          }
        });
      };
    },
    goBack() {
      const th = this;
      th.$router.push({
        path: "visit"
      });
    }
  }
};
</script>